<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <!-- model的本质是对象 ，但是userinfos是个数组  -->
      <el-form class="member-info" :model="{ userInfos }" ref="usersFrom">
        <div class="member-info-item" v-for="(user, index) in userInfos" :key="index">
          <el-form-item
            class="nameForm"
            label="乘机人姓名"
            :prop="`userInfos[${index}].username`"
            :rules="[
              { required: true, message: '请输入乘机人姓名', trigger: 'blur' }
            ]"
          >
            <el-input placeholder="姓名" class="input-with-select" v-model="user.username"></el-input>
          </el-form-item>

          <el-form-item
            label="证件号码"
            :prop="`userInfos[${index}].id`"
            :rules="[
              {
                required: true,
                message: '请输入身份证号',
                trigger: 'blur'
              },
              {
                pattern: /^\d{18}$/,
                message: '身份证不合法',
                trigger: 'blur'
              }
            ]"
          >
            <el-input placeholder="证件号码" class="input-with-select" v-model="user.id"></el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">添加乘机人</el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <el-checkbox-group v-model="checkList">
          <div class="insurance-item" v-for="item in data.insurances" :key="item.id">
            <el-checkbox :label="item.id" border>
              {{
              `${item.type}：￥${item.price}/份×1 最高赔付${item.compensation}`
              }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
        <el-checkbox v-model="checked">是否需要发票</el-checkbox>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="60px"
          :model="{
            contactName,
            contactPhone,
            captcha
          }"
          :rules="contactRules"
          ref="contactFrom"
        >
          <el-form-item label="姓名" prop="contactName" label-width="80px">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone" label-width="80px">
            <el-input placeholder="请输入内容" v-model="contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="captcha" label-width="80px">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" class="submit" @click="handleSubmit">提交订单</el-button>
      </div>
    </div>
    <!-- 登录对话框 -->
    <el-dialog  :show-close="false" title="请先进行登录" :visible.sync="dialogVisible" width="30%">
      <!-- 内容填充 -->
      <div class="login" style="position:relative;">
        <LoginComponent @DialogClose="DialogClose" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import LoginComponent from '@/components/user/LoginComponent'
export default {
  components:{
    LoginComponent
  },
  props: {
    data: Object,
  },
  data() {
    return {
      // 登陆框的显示隐藏
      dialogVisible:false,
      userInfos: [
        {
          username: '',
          id: '347288399908763727',
        },
      ],
      checkList: [],
      contactName: '小组',
      contactPhone: '15098374822',
      checked: false,
      captcha: '',
      contactRules: {
        contactName: [
          { required: true, message: '请输入联系人', trigger: 'blur' },
        ],
        contactPhone: [
          {
            required: true,
            message: '请输入联系人手机',
            trigger: 'blur',
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
        captcha: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  // 深度监听属性,immediate:从别的页面一进来就执行，不必等到数据发生改变才执行
  watch: {
    userInfos: {
      // console.log("乘机人变");
      handler() {
        this.CalcTotalPrice()
      },
      immediate: true,
    },
    checkList: {
      handler() {
        this.CalcTotalPrice()
      },
      immediate: true,
      // console.log("选了保险");
    },
  },
  mounted() {
    // console.log("表单", this.data);
    this.CalcTotalPrice()
  },

  methods: {
    //计算总价格
    CalcTotalPrice() {
      let tprice = 0
      tprice = this.data.seat_infos.org_settle_price * this.userInfos.length
      this.data.insurances.forEach((ele) => {
        // console.log(ele);
        if (this.checkList.indexOf(ele.id) >= 0) {
          tprice += ele.price * this.userInfos.length
        }
      })
      // console.log(tprice);
      this.$emit('changePrice', {
        tprice,
        num: this.userInfos.length,
      })
    },
    // 添加乘机人
    handleAddUsers() {
      this.userInfos.push({
        username: '',
        id: '',
      })
    },
    // 移除乘机人
    handleDeleteUser(index) {
      this.userInfos.splice(index, 1)
    },

    // 发送手机验证码
    handleSendCaptcha() {
      if (!this.contactPhone) {
        this.$message.error('请先输入手机号')
        return
      }
      this.$axios({
        method: 'post',
        url: '/captchas',
        data: {
          tel: this.contactPhone,
        },
      }).then((res) => {
        // console.log(res);
        if (res.data.code === '000000') {
          this.$message.success('验证码已发送')
        }
      })
    },

    // 提交订单
    async handleSubmit() {
      // 判断是否登陆
      if (!this.$store.state.user.userInfo.token) {
        return this.dialogVisible = true
      }

      // console.log(this.$route.query.id);
      // let id = Number(this.$route.query.id);
      // console.log(typeof id);
      // 使用async与await方式校验表单
      let isValidUsersFrom = await this.$refs.usersFrom
        .validate()
        .catch((e) => {})
      let isValidContactFrom = await this.$refs.contactFrom
        .validate()
        .catch((e) => {})
      // console.log(this.data);
      if (isValidUsersFrom && isValidContactFrom) {
        let data = {
          users: this.userInfos,
          insurances: this.checkList,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          invoice: this.checked,
          seat_xid: this.$route.query.seat_xid,
          air: Number(this.$route.query.id),
          captcha: this.captcha,
        }
        this.$axios({
          url: '/airorders',
          method: 'post',
          data: data,
          headers: {
            Authorization: 'Bearer ' + this.$store.state.user.userInfo.token,
          },
        }).then((res) => {
          // console.log(111, res);

          if (res.data.message == '订单提交成功') {
            this.$message.success(res.data.message)
            setTimeout(() => {
              this.$router.push('/air/pay?id=' + res.data.data.id)
            }, 800)
          }
        })
      }
    },
    DialogClose(){
      console.log(123456)
      this.$message.success('登录成功，您可以进行购买了')
      this.dialogVisible = false
    }
  },
}
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
  .nameForm {
    margin-bottom: 20px;
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
</style>
